﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Ports;
using Microsoft.Win32;
using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace SerialPortCommunicate
{
    class MySerialPort
    {
        private SerialPort serialPort = new SerialPort();

        // 串口打开标识
        public bool open = false;

        // 接收事件
        public event Action<string> receiveEvent;
        string sValue = "";
        //初始化
        public void initBy()
        {
            RegistryKey keyCom = Registry.LocalMachine.OpenSubKey("Hardware\\DeviceMap\\SerialComm");
            if (keyCom != null)
            {
                string[] sSubKeys = keyCom.GetValueNames();
                foreach (string sName in sSubKeys)
                {
                    sValue = (string)keyCom.GetValue(sName);
                    serialPort.PortName = sValue;
                }
            }
            else
            {
                MessageBox.Show("没有检测到串口，请先连接底板上的USB再打开软件！", "Error");
                return;
            }
        }

        //打开端口
        public void openBy(string portName, int baudRate)
        {
            try
            {

                serialPort.DataReceived += new SerialDataReceivedEventHandler(SerialPortDataReceived);
                serialPort.BaudRate = 115200;
                serialPort.DataBits = 8;
                serialPort.StopBits = StopBits.One;
                serialPort.Parity = Parity.None;
                serialPort.Open();            
                open = true;
            }
            catch (Exception)
            {
                MessageBox.Show("没有检测到串口，请先连接底板上的USB再打开软件！", "Error");
            }
        }

        //关闭端口
        public void close()
        {
            try
            {
                serialPort.Close();
                open = false;
            }
            catch (Exception)
            {
                throw;
            }
        }

        //用来存放接收的端口字符串
        public string receiveMessage = "";
        //channel1的值
        public string channel1_value = "000001";
        //channel2的值
        public string channel2_value = "000002";
        //接收函数
        private void SerialPortDataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                string str = serialPort.ReadExisting();//字符串方式读
                receiveMessage = "";//先清除上一次的数据
                receiveMessage += str;
                //MessageBox.Show(receiveMessage);
                //如果接收的字符串为ADERROROK
                if (str == "ADERROOK")
                {
                    MessageBox.Show("指令异常，请重新输入！");
                }

                else
                {
                    //如果接收的字符串不是AD7746OK，就应该是best000000000000ron这一串
                    if (str != "AD7746OK")
                    {
                        if (Regex.IsMatch(str, @"^best") && Regex.IsMatch(str, @"ron$") && str.Length == 19)
                        {
                            channel1_value = str.Substring(4, 6);
                            channel2_value = str.Substring(10, 6);
                            MessageBox.Show(channel1_value);
                            MessageBox.Show(channel2_value);
                        }
                        else
                        {
                            MessageBox.Show("输出字符串有误");
                        }
                    }
                    //接收字符串为AD7746，说明指令正确，不做处理
                    else
                    {
                        return;
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }


        public static string queryData = "ATREADOK";
        private static string startMonitoring = "ATSTAROK";
        private static string endMonitoring = "ATSTOPOK";
        private static string reset = "ATRESTOK";

        private static string setChannel1 = "AT0700OK";
        private static string setChannel2 = "AT0701OK";
        private static string setDoubleChannel = "AT0701OK";

        private static string precisionNormal = "AT0703OK";
        private static string precisionHigh = "AT0704OK";

        private static string workModeSingle = "AT0705OK";
        private static string workModeDiffer = "AT0706OK";

        private static string speedNormal = "AT0900OK";
        private static string speedTwopointFreq = "AT0901OK";

        private static string forwaIncentiveEXCB = "AT0902OK";
        private static string reverIncentiveEXCB = "AT0903OK";
        private static string forwaIncentiveEXCA = "AT0904OK";
        private static string reverIncentiveEXCA = "AT0905OK";

        private static string vddOneEighth = "AT0906OK";
        private static string vddQuarter = "AT0907OK";
        private static string vddThreeEighths = "AT0908OK";
        private static string vddHalf = "AT0909OK";

        private static string converModeSingle = "AT0A00OK";
        private static string converModeContinue = "AT0A01OK";

        private static string converTime11 = "AT0A02OK";
        private static string converTime12 = "AT0A03OK";
        private static string converTime20 = "AT0A04OK";
        private static string converTime38 = "AT0A05OK";
        private static string converTime62 = "AT0A06OK";
        private static string converTime77 = "AT0A07OK";
        private static string converTime92 = "AT0A08OK";
        private static string converTime110 = "AT0A09OK";

        private static string positiveCalibValue = "AT0B**OK";
        private static string negativeCalibValue = "AT0C**OK";

        private static string returnAllValues = "ATRRRROK";

        public void write(string e)
        {
            try
            {
                //发送数据
                if (serialPort.IsOpen)
                {
                    //如果串口开启
                    serialPort.Write(e);//写数据
                }
                else
                {
                    MessageBox.Show("串口未打开");
                }

            }
            catch (Exception)
            {
                throw;
            }
        }

        public void query_Data()
        {
            write(queryData);
        }
        //开始监控
        public void start_Monitoring()
        {
            write(startMonitoring);
        }
        //结束监控
        public void end_Monitoring()
        {
            write(endMonitoring);
        }
        //复位7746
        public void re_Set()
        {
            write(reset);
        }
        //通道1
        public void set_Channel1()
        {
            write(setChannel1);
        }
        //通道2
        public void set_Channel2()
        {
            write(setChannel2);
        }
        //双通道
        public void set_DoubleChannel()
        {
            write(setDoubleChannel);
        }
        //正常
        public void precision_Normal()
        {
            write(precisionNormal);
        }
        //高精度
        public void precision_High()
        {
            write(precisionHigh);
        }
        //单端模式
        public void work_ModeSingle()
        {
            write(workModeSingle);
        }
        //差分模式
        public void work_ModeDiffer()
        {
            write(workModeDiffer);
        }
        //正常速度
        public void speed_Normal()
        {
            write(speedNormal);
        }
        //二分频
        public void speed_TwopointFreq()
        {
            write(speedTwopointFreq);
        }
        //EXCB正向激励
        public void forwa_IncentiveEXCB()
        {
            write(forwaIncentiveEXCB);
        }
        //EXCB反向激励
        public void rever_IncentiveEXCB()
        {
            write(reverIncentiveEXCB);
        }
        //EXCA正向激励
        public void forwa_IncentiveEXCA()
        {
            write(forwaIncentiveEXCA);
        }
        //EXCA反向激励
        public void rever_IncentiveEXCA()
        {
            write(reverIncentiveEXCA);
        }
        //1/8vdd
        public void vdd_OneEighth()
        {
            write(vddOneEighth);
        }
        //1/4vdd
        public void vdd_Quarter()
        {
            write(vddQuarter);
        }
        //3/8vdd
        public void vdd_ThreeEighths()
        {
            write(vddThreeEighths);
        }
        //1/2vdd
        public void vdd_Half()
        {
            write(vddHalf);
        }
        //单次转换
        public void conver_ModeSingle()
        {
            write(converModeSingle);
        }
        //连续转换
        public void conver_ModeContinue()
        {
            write(converModeContinue);
        }
        //11ms
        public void conver_Time11()
        {
            write(converTime11);
        }
        //12ms
        public void conver_Time12()
        {
            write(converTime12);
        }
        //20ms
        public void conver_Time20()
        {
            write(converTime20);
        }
        //38ms
        public void conver_Time38()
        {
            write(converTime38);
        }
        //62ms
        public void conver_Time62()
        {
            write(converTime62);
        }
        //77ms
        public void conver_Time77()
        {
            write(converTime77);
        }
        //92ms
        public void conver_Time92()
        {
            write(converTime92);
        }
        //110ms
        public void conver_Time110()
        {
            write(converTime110);
        }
        //正校准值
        public void positive_CalibValue()
        {
            write(positiveCalibValue);
        }
        //负校准值
        public void negative_CalibValue()
        {
            write(negativeCalibValue);
        }
        //返回所有寄存器的值
        public void return_AllValues()
        {
            write(returnAllValues);
        }

    }
}
